package com.bocai.grainshop.order.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bocai.common.exception.HasWareException;
import com.bocai.common.to.mq.SeckillOrderTo;
import com.bocai.common.to.mq.WareOrdersn;
import com.bocai.common.utils.R;
import com.bocai.common.vo.MemberVo;
import com.bocai.grainshop.order.constant.OrderConstant;
import com.bocai.grainshop.order.entity.OrderItemEntity;
import com.bocai.grainshop.order.enume.OrderStatusEnum;
import com.bocai.grainshop.order.feign.CartFeignService;
import com.bocai.grainshop.order.feign.MemberFeignService;
import com.bocai.grainshop.order.feign.ProductFeignService;
import com.bocai.grainshop.order.feign.WareFeignService;
import com.bocai.grainshop.order.interceptor.WebInterceptor;
import com.bocai.grainshop.order.service.OrderItemService;
import com.bocai.grainshop.order.to.OrderCreateTo;
import com.bocai.grainshop.order.to.SpuInfoVo;
import com.bocai.grainshop.order.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bocai.common.utils.PageUtils;
import com.bocai.common.utils.Query;

import com.bocai.grainshop.order.dao.OrderDao;
import com.bocai.grainshop.order.entity.OrderEntity;
import com.bocai.grainshop.order.service.OrderService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;




@Slf4j
@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {


    @Autowired
    private MemberFeignService memberFeignService;

    @Autowired
    private CartFeignService cartFeignService;

    @Autowired
    private ThreadPoolExecutor executor;

    @Autowired
    private WareFeignService wareFeignService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private ProductFeignService productFeignService;

    @Autowired
    private OrderItemService orderItemService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<>()
        );

        return new PageUtils(page);
    }


    @Override
    public Integer getInfoByOrderSn(String orderSn) {
        OrderEntity order_sn = this.getOne(new QueryWrapper<OrderEntity>().eq("order_sn", orderSn));
        return order_sn==null?null:order_sn.getStatus();
    }

    /**
     * @Author: SunJinbo
     * @Description  延迟关单
     * @Param [order]
     * @return void
     * @Data Created in 2022/4/25 18:44
     */
    @Override
    public void OrderClose(OrderEntity order) {
        OrderEntity byId = this.getById(order.getId());
        //查询的订单还是待付款状态
        if(byId.getStatus() == OrderStatusEnum.CREATE_NEW.getCode()){
            byId.setStatus(OrderStatusEnum.CANCLED.getCode());

            //TODO 模拟网络波动  关单超时   Thread.sleep(10000);

            this.updateById(byId);
            //TODO 关单完成 发送消息到队列 队列在路由到库存解锁
            log.info("订单号->{}"+byId.getOrderSn());

            WareOrdersn ordersn = new WareOrdersn();
            ordersn.setOrderSn(byId.getOrderSn());
            try {
                //TODO  保证消息一定发出去 每一个消息都做好日志 (给数据库添加一个详细的消息表)
                //TODO  定期扫描数据库，把失败的消息重新发生一遍
                rabbitTemplate.convertAndSend("order-event-exchange","order.release.other",ordersn);
            } catch (Exception e) {
                // TODO 发生异常 将消息重试重新发生
            }
        }
    }

    /**
     * @Author: SunJinbo
     * @Description  获取订单详情页信息
     * @Param []
     * @return com.bocai.grainshop.order.vo.OrderConfirmVo
     * @Data Created in 2022/4/21 16:51
     */
    @Override
    public OrderConfirmVo OrderConfirm() {
        //获取登录的人的信息
        MemberVo memberVo = WebInterceptor.loginUser.get();
        //准备要封装的对象
        OrderConfirmVo confirmVo = new OrderConfirmVo();

        log.info("主线程{}"+Thread.currentThread().getId());

        //解决多线程丢失请求头
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();

        CompletableFuture<Void> getAddress = CompletableFuture.runAsync(() -> {
            //每一个请求共享主线程的请求数据
            RequestContextHolder.setRequestAttributes(requestAttributes);
            log.info("子线程getAddress{}"+Thread.currentThread().getId());
            /** 会员收获地址列表 **/
            List<MemberAddressVo> memberId = memberFeignService.getAddressByMemberId(memberVo.getId());
            if (memberId != null && memberId.size() > 0) {
                confirmVo.setMemberAddressVos(memberId);
            }
        }, executor);

        /** 所有选中的购物项
         *
         * feign远程调用 丢失请求头问题
         * 解决:创建一个feign调用前的请求拦截器
         *
         * **/
        CompletableFuture<Void> getCartItems = CompletableFuture.runAsync(() -> {
            RequestContextHolder.setRequestAttributes(requestAttributes);
            log.info("子线程getCartItems{}"+Thread.currentThread().getId());
            List<OrderItemVo> userCartItems = cartFeignService.getUserCartItems();
            if (userCartItems != null && userCartItems.size() > 0) {
                confirmVo.setItems(userCartItems);
            }
        }, executor).thenRunAsync(()->{
            log.info("then线程getCartItems{}"+Thread.currentThread().getId());
            List<Long> collect = confirmVo.getItems().stream().map((item) -> item.getSkuId()).collect(Collectors.toList());
            R hasStock = wareFeignService.getSkuHasStock(collect);

            Object code = hasStock.get("code");
            String s = JSON.toJSONString(code);
            Integer codeNum = JSON.parseObject(s, new TypeReference<Integer>() {
            });
            if(codeNum == 0){
                Object vos = hasStock.get("vos");
                String vosS = JSON.toJSONString(vos);
                List<SkuStockVo> skuStockVos = JSON.parseObject(vosS, new TypeReference<List<SkuStockVo>>() {
                });
                if(skuStockVos != null && skuStockVos.size()>0){
                    Map<Long, Boolean> booleanMap = skuStockVos.stream().collect(Collectors.toMap(SkuStockVo::getSkuId, SkuStockVo::getHasStock));
                    confirmVo.setStocks(booleanMap);
                }
            }

        },executor);


        /** 发票记录 **/ /** 优惠券（会员积分） **/
        if(memberVo.getIntegration() != null){
            confirmVo.setIntegration(memberVo.getIntegration());
        }
        //其他信息 类自动封装

        //TODO 防重令牌
        String token = UUID.randomUUID().toString().replace("_", "");

        confirmVo.setOrderToken(token);
        //服务器保存防重令牌
        redisTemplate.opsForValue().set(OrderConstant.USER_ORDER_TOKEN_PREFIX+memberVo.getId(),token,30, TimeUnit.MINUTES);

        //多线程阻塞等待全部完成
        try {
            CompletableFuture.allOf(getAddress,getCartItems).get();
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
        return confirmVo;
    }


//    @GlobalTransactional AT模式不推荐高并发
    @Transactional
    //创建订单  验令牌 验价格 锁库存
    @Override
    public SubmitOrderResponseVo createOrder(OrderSubmitVo orderSubmitVo) {
        //创建准备返回的对象
        SubmitOrderResponseVo responseVo = new SubmitOrderResponseVo();
        //获取登录的用户信息
        MemberVo memberVo = WebInterceptor.loginUser.get();
        //获取和删除令牌 必须保证原子性  lua脚本
        String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
        //获取前台传来的token
        String orderToken = orderSubmitVo.getOrderToken();
        //执行脚本  原子性验证和删除令牌 【0】失败 【1】成功
        Long bool = redisTemplate.execute(new DefaultRedisScript<>(script, Long.class), Arrays.asList(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberVo.getId()), orderToken);
        if(bool == 1l){
            //验证成功 封装数据
            OrderCreateTo order= creteOrder(orderSubmitVo.getAddrId());
            BigDecimal payAmount = order.getOrder().getPayAmount();
            BigDecimal payPrice = orderSubmitVo.getPayPrice();
            if(Math.abs(payAmount.subtract(payPrice).doubleValue()) < 0.01){
                //可接受误差范围内
                //保存订单所有数据
                saveOrder(order);
                //订单保存成功  远程锁定库存
                WareSkuLockVo skuLockVo = new WareSkuLockVo();
                skuLockVo.setOrderSn(order.getOrder().getOrderSn());
                List<OrderItemVo> collect = order.getOrderItems().stream().map((it) -> {
                    OrderItemVo orderItemVo = new OrderItemVo();
                    orderItemVo.setSkuId(it.getSkuId());
                    orderItemVo.setCount(it.getSkuQuantity());
                    orderItemVo.setTitle(it.getSkuName());
                    return orderItemVo;
                }).collect(Collectors.toList());
                skuLockVo.setLocks(collect);
                //远程锁库存
                R r = wareFeignService.lockWare(skuLockVo);
                Object code = r.get("code");
                String s = JSON.toJSONString(code);
                Integer codeNum = JSON.parseObject(s, new TypeReference<Integer>() {
                });
                if(codeNum == 0){
                    responseVo.setOrder(order.getOrder());
                    responseVo.setCode(200);
//                    int a = 10 /0;
                    //TODO 订单创建成功！ 发送消息
                    rabbitTemplate.convertAndSend("order-event-exchange","order.create.order",order.getOrder());
                    return responseVo;
                }else {
                    //锁定失败
                    throw new HasWareException(1l);
                }
            }else {
                responseVo.setCode(1);
                return responseVo;
            }
        }else {
            responseVo.setCode(2);
            return responseVo;
        }
    }

    //保存订单的私有方法
    private void saveOrder(OrderCreateTo order) {
        //保存订单
        OrderEntity orderEntity = order.getOrder();
        orderEntity.setCreateTime(new Date());
        orderEntity.setModifyTime(new Date());
        this.save(orderEntity);
        //保存订单项
        List<OrderItemEntity> collect = order.getOrderItems().stream().map(o -> {
            o.setOrderId(orderEntity.getId());
            return o;
        }).collect(Collectors.toList());

        orderItemService.saveBatch(collect);
    }

    //创建订单的私有方法
    private OrderCreateTo creteOrder(Long addrId){
        //准备封装返回的对象
        OrderCreateTo orderCreateTo = new OrderCreateTo();

        //准备订单属性
        OrderEntity orderEntity = new OrderEntity();
        //创建订单号  mybatis工具包
        String order_sn = IdWorker.getTimeId();
        orderEntity.setOrderSn(order_sn);

        //远程调用查库存
        R fare = wareFeignService.getFare(addrId);
        Object code = fare.get("code");
        String s = JSON.toJSONString(code);
        Integer codeNum = JSON.parseObject(s, new TypeReference<Integer>() {
        });
        if(codeNum == 0){
            Object data = fare.get("data");
            String dataS = JSON.toJSONString(data);
            FareVo fareVo = JSON.parseObject(dataS, new TypeReference<FareVo>() {
            });
            if(fareVo!=null && fareVo.getFare()!=null && fareVo.getAddress() != null){
                //设置订单的基本信息
                createSimpleMessage(orderEntity, fareVo);
                orderCreateTo.setOrder(orderEntity);
                //获取所有的订单项信息
                List<OrderItemVo> userCartItems = cartFeignService.getUserCartItems();
                if(userCartItems != null && userCartItems.size() > 0){
                    List<OrderItemEntity> collect = userCartItems.stream().map(CartItem -> {
                        OrderItemEntity orderItemEntity = OrderItemCreate(CartItem,order_sn);
                        return orderItemEntity;
                    }).collect(Collectors.toList());
                  orderCreateTo.setOrderItems(collect);
                }
            }
        }

        //验证价格
        comcupePrice(orderEntity,orderCreateTo.getOrderItems());

        return orderCreateTo;
    }

    //验价格方法
    private void comcupePrice(OrderEntity orderEntity, List<OrderItemEntity> orderItems) {
        BigDecimal promotion = new BigDecimal("0");
        BigDecimal coupon = new BigDecimal("0");
        BigDecimal ingetaration = new BigDecimal("0");
        BigDecimal real= new BigDecimal("0");
        BigDecimal gift = new BigDecimal("0");
        BigDecimal growth = new BigDecimal("0");
        for (OrderItemEntity orderItem : orderItems) {
            promotion = promotion.add(orderItem.getPromotionAmount());
            coupon = coupon.add(orderItem.getCouponAmount());
            ingetaration = ingetaration.add(orderItem.getIntegrationAmount());
            real = real.add(orderItem.getRealAmount());
            gift = gift.add(new BigDecimal(orderItem.getGiftIntegration().toString()));
            growth = growth.add(new BigDecimal(orderItem.getGiftGrowth().toString()));
        }
        orderEntity.setCouponAmount(coupon);
        orderEntity.setIntegrationAmount(ingetaration);
        orderEntity.setPromotionAmount(promotion);
        orderEntity.setTotalAmount(real);
        orderEntity.setPayAmount(real.add(orderEntity.getFreightAmount()));
        orderEntity.setIntegration(gift.intValue());
        orderEntity.setGrowth(growth.intValue());
        orderEntity.setDeleteStatus(0);
    }

    //封装基本信息
    private void createSimpleMessage(OrderEntity orderEntity, FareVo fareVo) {
        orderEntity.setFreightAmount(fareVo.getFare());
        orderEntity.setReceiverCity(fareVo.getAddress().getCity());
        orderEntity.setReceiverDetailAddress(fareVo.getAddress().getDetailAddress());
        orderEntity.setReceiverName(fareVo.getAddress().getName());
        orderEntity.setReceiverPhone(fareVo.getAddress().getPhone());
        orderEntity.setReceiverPostCode(fareVo.getAddress().getPostCode());
        orderEntity.setReceiverProvince(fareVo.getAddress().getProvince());
        orderEntity.setReceiverRegion(fareVo.getAddress().getRegion());
        orderEntity.setPayType(1);
        orderEntity.setAutoConfirmDay(7);
        orderEntity.setMemberId(fareVo.getAddress().getMemberId());
        orderEntity.setDeliveryTime(new Date());
        orderEntity.setReceiveTime(new Date());
        orderEntity.setCommentTime(new Date());
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        //远程查会员名
        R info = memberFeignService.info(fareVo.getAddress().getMemberId());
        Object code = info.get("code");
        String s = JSON.toJSONString(code);
        Integer codeNum = JSON.parseObject(s, new TypeReference<Integer>() {
        });
        if(codeNum == 0){
            Object member = info.get("member");
            String toJSONString = JSON.toJSONString(member);
            MemberRVo memberRVo = JSON.parseObject(toJSONString, new TypeReference<MemberRVo>() {
            });
            orderEntity.setMemberUsername(memberRVo.getUsername());
        }
    }

    //封装订单项的基本信息
    private OrderItemEntity OrderItemCreate(OrderItemVo cartItem,String order_sn) {
        OrderItemEntity entity = new OrderItemEntity();
        //设置订单号
        entity.setOrderSn(order_sn);
        //封装 sku信息
        entity.setSkuId(cartItem.getSkuId());
        entity.setSkuName(cartItem.getTitle());
        entity.setSkuPic(cartItem.getImage());
        entity.setSkuPrice(cartItem.getPrice());
        String skuAttr = StringUtils.collectionToDelimitedString(cartItem.getSkuAttrValues(), ";");
        entity.setSkuAttrsVals(skuAttr);
        entity.setSkuQuantity(cartItem.getCount());
        //设置积分信息
        entity.setGiftGrowth(cartItem.getPrice().multiply(new BigDecimal(cartItem.getCount())).intValue());
        entity.setGiftIntegration(cartItem.getPrice().multiply(new BigDecimal(cartItem.getCount())).intValue());
        //设置spu信息
        R infoBySpuId = productFeignService.getSpuInfoBySpuId(cartItem.getSkuId());
        Object code = infoBySpuId.get("code");
        String s = JSON.toJSONString(code);
        Integer codeNum = JSON.parseObject(s, new TypeReference<Integer>() {
        });
        if(codeNum == 0){
            Object info = infoBySpuId.get("info");
            String toJSONString = JSON.toJSONString(info);
            SpuInfoVo spuInfoVo = JSON.parseObject(toJSONString, new TypeReference<SpuInfoVo>() {
            });
           entity.setSpuId(spuInfoVo.getId());
           entity.setSpuBrand(spuInfoVo.getBrandId().toString());
           entity.setSpuName(spuInfoVo.getSpuName());
           entity.setCategoryId(spuInfoVo.getCatalogId());
        }
        //设置订单项的价格信息
        entity.setPromotionAmount(new BigDecimal("0"));
        entity.setCouponAmount(new BigDecimal("0"));
        entity.setIntegrationAmount(new BigDecimal("0"));
        //当前订单的实际金额
        BigDecimal orgin = entity.getSkuPrice().multiply(new BigDecimal(entity.getSkuQuantity().toString()));
        BigDecimal subtract = orgin.subtract(entity.getCouponAmount())
                .subtract(entity.getIntegrationAmount())
                .subtract(entity.getPromotionAmount());
        entity.setRealAmount(subtract);
        return entity;
    }

    /**
     * @Author: SunJinbo
     * @Description  获取订单的详细信息 通过订单号
     * @Param [orderSn]
     * @return com.bocai.grainshop.order.vo.PayVo
     * @Data Created in 2022/4/27 14:58
     */
    @Override
    public PayVo getOrderPay(String orderSn) {
        PayVo payVo = new PayVo();

        OrderEntity orderInfo = this.getOne(new QueryWrapper<OrderEntity>().eq("order_sn", orderSn));

        //保留两位小数点，向上取值
        BigDecimal payAmount = orderInfo.getPayAmount().setScale(2, BigDecimal.ROUND_UP);
        payVo.setTotal_amount(payAmount.toString());
        payVo.setOut_trade_no(orderInfo.getOrderSn());

        //查询订单项的数据
        List<OrderItemEntity> orderItemInfo = orderItemService.list(
                new QueryWrapper<OrderItemEntity>().eq("order_sn", orderSn));
        OrderItemEntity orderItemEntity = orderItemInfo.get(0);

        payVo.setSubject(orderItemEntity.getSkuName());

        return payVo;
    }

    /**
     * @Author: SunJinbo
     * @Description  支付后的查询出所有的订单和订单项信息
     * @Param [params]
     * @return com.bocai.common.utils.PageUtils
     * @Data Created in 2022/4/27 15:36
     */
    @Override
    public PageUtils queryWithItem(Map<String, Object> params) {
        MemberVo memberVo = WebInterceptor.loginUser.get();
        IPage<OrderEntity> member_id = this.page(new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>().eq("member_id", memberVo.getId()).orderByDesc("order_sn")
        );
        List<OrderEntity> collect = member_id.getRecords().stream().map(o -> {
            List<OrderItemEntity> order_sn = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", o.getOrderSn()));
            o.setItems(order_sn);
            o.setStatus(2);
            return o;
        }).collect(Collectors.toList());

        //修改数据库订单状态
        List<OrderEntity> id = this.list(new QueryWrapper<OrderEntity>().orderByDesc("id"));
        if(id != null && id.size()>0){
            id.get(0).setStatus(2);
            this.updateById(id.get(0));
        }
        member_id.setRecords(collect);
        //TODO 支付成功后修改购物车内容
        updateCartItems();

        return new PageUtils(member_id);
    }

    /**
     * @Author: SunJinbo
     * @Description  支付成功后修改购物车内容
     * @Param []
     * @return void
     * @Data Created in 2022/5/4 20:08
     */
    private void updateCartItems(){
       R r = cartFeignService.updateCartItems();
        Object code = r.get("code");
        String s = JSON.toJSONString(code);
        Integer codeNum = JSON.parseObject(s, new TypeReference<Integer>() {
        });
        if(codeNum != 0){
            log.info("购物车异常！");
        }
    }

    /**
     * @Author: SunJinbo
     * @Description  秒杀订单创建
     * @Param []
     * @return void
     * @Data Created in 2022/4/30 19:57
     */
    @Override
    public void createSeckillOrder(SeckillOrderTo to) {
        //准备需要保存的订单对象
        OrderEntity orderEntity = new OrderEntity();
        //设置to传来的基本信息
        orderEntity.setOrderSn(to.getOrderSn());
        orderEntity.setMemberId(to.getMemberId());
        orderEntity.setCreateTime(new Date());
        orderEntity.setMemberUsername(to.getUsername());
        orderEntity.setTotalAmount(to.getSeckillPrice());
        orderEntity.setPayAmount(to.getSeckillPrice());
        orderEntity.setFreightAmount(new BigDecimal("0"));
        orderEntity.setPayType(1);
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        orderEntity.setAutoConfirmDay(7);
        orderEntity.setReceiverName(to.getUsername());
        orderEntity.setModifyTime(new Date());
        //TODO  mq关单
        this.save(orderEntity);
        //保存订单项信息
        OrderItemEntity itemEntity = new OrderItemEntity();
        itemEntity.setOrderId(orderEntity.getId());
        itemEntity.setOrderSn(to.getOrderSn());
        //查询spu信息
        R vo = productFeignService.getSpuInfoBySpuId(to.getSkuId());
        Object code = vo.get("code");
        String s = JSON.toJSONString(code);
        Integer codeNum = JSON.parseObject(s, new TypeReference<Integer>() {
        });
        if(codeNum == 0){
            Object info = vo.get("info");
            String toJSONString = JSON.toJSONString(info);
            SpuInfoVo spuInfoVo = JSON.parseObject(toJSONString, new TypeReference<SpuInfoVo>() {
            });
            itemEntity.setSpuName(spuInfoVo.getSpuName());
            itemEntity.setSpuId(spuInfoVo.getId());
            itemEntity.setSpuBrand(spuInfoVo.getBrandId().toString());
            itemEntity.setCategoryId(spuInfoVo.getCatalogId());
        }
        //设置sku信息
        R info = productFeignService.info(to.getSkuId());
        Object o = info.get("code");
        String jsonString = JSON.toJSONString(o);
        Integer codeNumber = JSON.parseObject(jsonString, new TypeReference<Integer>() {
        });

        if(codeNumber == 0){
            Object skuInfo = info.get("skuInfo");
            String sku = JSON.toJSONString(skuInfo);
            SkuInfoVo skuInfoVo = JSON.parseObject(sku, SkuInfoVo.class);
            List<String> salaAttrToString = productFeignService.getSalaAttrToString(skuInfoVo.getSkuId());
            skuInfoVo.setAttrSaleAttr(salaAttrToString);
            itemEntity.setSkuId(skuInfoVo.getSkuId());
            itemEntity.setSkuName(skuInfoVo.getSkuName());
            itemEntity.setSkuPic(skuInfoVo.getSkuDefaultImg());
            itemEntity.setSkuPrice(skuInfoVo.getSkuPrice());
            String join = org.apache.commons.lang.StringUtils.join(salaAttrToString, ",");
            log.info("{}"+join);
            itemEntity.setSkuAttrsVals(join);
        }

        itemEntity.setPromotionAmount(new BigDecimal("0"));
        itemEntity.setCouponAmount(new BigDecimal("0"));
        itemEntity.setIntegrationAmount(new BigDecimal("0"));
        itemEntity.setRealAmount(to.getSeckillPrice());
        itemEntity.setGiftIntegration(to.getSeckillPrice().intValue());
        itemEntity.setGiftGrowth(to.getSeckillPrice().intValue());
        orderItemService.save(itemEntity);
    }

    /**
     * @Author: SunJinbo
     * @Description  获取所有已完成的订单id集合
     * @Param []
     * @return java.util.List<java.lang.Long>
     * @Data Created in 2022/5/4 20:43
     */
    @Override
    public List<Long> getFinshOrderSkuArray() {
        MemberVo memberVo = WebInterceptor.loginUser.get();
        List<OrderEntity> member_id = this.list(new QueryWrapper<OrderEntity>().eq("member_id", memberVo.getId()).eq("status",2));
        List<Long> skuIDs = new ArrayList<>();
        if(member_id != null && member_id.size() >0){
            for (OrderEntity m : member_id) {
                List<OrderItemEntity> order_id = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_id", m.getId()));
                if(order_id != null && order_id.size() > 0 ){
                    for (OrderItemEntity entity : order_id) {
                        Long skuId = entity.getSkuId();
                        if(entity.getSkuQuantity() != null){

                            Integer count = entity.getSkuQuantity();
                            for (Integer i = 0; i < count; i++) {
                                skuIDs.add(skuId);
                            }
                        }
                    }
                }
            }
            return skuIDs;
        }
        return null;
    }

    @Override
    public PageUtils queryWith(Map<String, Object> map) {
        MemberVo memberVo = WebInterceptor.loginUser.get();
        IPage<OrderEntity> page = this.page(new Query<OrderEntity>().getPage(map),
                new QueryWrapper<OrderEntity>().eq("member_id", memberVo.getId()).orderByDesc("order_sn"));
        //构建订单项
        List<OrderEntity> records = page.getRecords();
        List<OrderEntity> orderSn = records.stream().map(o -> {
            List<OrderItemEntity> order_sn = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", o.getOrderSn()));
            o.setItems(order_sn);
            return o;
        }).collect(Collectors.toList());
        page.setRecords(orderSn);
        return new PageUtils(page);
    }
}